package crawler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.List;

import util.Constants;

public class Writer {
	private PrintStream stream;

	public Writer() {
		try {
			stream = new PrintStream(new File(Constants.TWEETS_DIR
					+ Constants.FILE_SEPARATOR + "coleta" + getId() + ".txt"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	private int getId() {
		File folder = new File(Constants.TWEETS_DIR);

		int id = -1;
		for (String file : folder.list()) {
			String idTemp = "";
			for (Character c : file.toCharArray()) {
				if (Character.isDigit(c)) {
					idTemp += c;
				}
			}
			if (idTemp.length() > 0) {
				id = Math.max(Integer.valueOf(idTemp) + 1, id);
			}
		}
		return id;
	}

	public void writeToFile(List<String> lines) {
		for (String string : lines) {
			System.out.println("===Saving Tweet: " + string);
			stream.append(string + Constants.LINE_SEPARATOR);
		}
	}

	public void closeFile() {
		stream.flush();
		stream.close();
	}
}
